package com.wxzz.elearing.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.wxzz.elearing.user.amqp.producer.UserMessageProducer;
import com.wxzz.elearing.user.dto.*;
import com.wxzz.elearing.user.entity.CommonCategory;
import com.wxzz.elearing.user.entity.EnterpriseImprove;
import com.wxzz.elearing.user.entity.EnterpriseOrganization;
import com.wxzz.elearing.user.entity.WxUser;
import com.wxzz.elearing.user.mapper.CommonCategoryMapper;
import com.wxzz.elearing.user.mapper.EnterpriseImproveMapper;
import com.wxzz.elearing.user.mapper.EnterpriseOrganizationMapper;
import com.wxzz.elearing.user.mapper.WxUserMapper;
import com.wxzz.elearing.user.service.IEnterpriseImproveService;
import com.wxzz.elearing.user.service.IWxUserService;
import com.wxzz.elearing.user.vo.EnterpriseImproveVo;
import com.wxzz.elearing.user.vo.SelectSumByEnterpriseImproveVo;
import com.wxzz.elearning.common.dto.FeignUserWalletDto;
import com.wxzz.elearning.common.dto.FeignWxUserDto;
import com.wxzz.elearning.common.dto.SystemMessageMqDto;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.utils.ExcelUtils;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 企业改善 服务实现类
 * </p>
 *
 * @author
 * @since 2021-05-17
 */
@Service
public class EnterpriseImproveServiceImpl extends ServiceImpl<EnterpriseImproveMapper, EnterpriseImprove> implements IEnterpriseImproveService {

    @Autowired
    private EnterpriseImproveMapper enterpriseImproveMapper;

    @Override
    public ReturnVO saveEnterpriseImprove(EnterpriseImprove enterpriseImprove) {
        if (enterpriseImprove.getId() == null) {
            enterpriseImproveMapper.insert(enterpriseImprove);
            //查询部门管理者id
            EnterpriseOrganization enterpriseOrganization = enterpriseOrganizationMapper.selectById(enterpriseImprove.getEnterpriseOrganizationId());
            //给部门管理者发消息
            if (enterpriseOrganization != null && enterpriseOrganization.getWxUserId() != null) {
                //todo 小程序订阅
                SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
                systemMessageMqDto.setMessageDetail("您有一条" + enterpriseImprove.getImproveTitle() + "待审核");
                systemMessageMqDto.setMessageTitle("改善成果审核待审核");
                systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
                    {
                        add(enterpriseOrganization.getWxUserId());
                    }
                });
                userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
            } else {
                throw new ServiceException("您所在的部门无部门管理者,请联系管理员添加");
            }
        } else {
            enterpriseImproveMapper.updateById(enterpriseImprove);
        }
        return new ReturnVO("企业改善", enterpriseImprove.getId());
    }

    @Override
    public ReturnVO listEnterpriseImprove(Integer type, Long enterpriseId, EnterpriseImproveDto enterpriseImproveDto) {
        PageHelper.startPage(enterpriseImproveDto.getCurPage(), enterpriseImproveDto.getMaxPage());
        QueryWrapper<EnterpriseImprove> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("enterprise_id", enterpriseId);
        Optional.ofNullable(enterpriseImproveDto.getEnterpriseOrganizationId()).ifPresent(e -> queryWrapper.eq("enterprise_organization_id", e));
        Optional.ofNullable(enterpriseImproveDto.getCommonCategoryId()).ifPresent(e -> queryWrapper.eq("common_category_id", e));
        //小程序只展示已通过的
        if (type != null && type == 0) {
            queryWrapper.eq("status", 1);
        }
        if (StringUtils.isNotBlank(enterpriseImproveDto.getImproveTitle())) {
            queryWrapper.like("improve_title", enterpriseImproveDto.getImproveTitle());
        }
        if (enterpriseImproveDto.getSort() != null && enterpriseImproveDto.getSort() == 0) {
            queryWrapper.orderByAsc("create_time");
        }
        if (enterpriseImproveDto.getSort() != null && enterpriseImproveDto.getSort() == 1) {
            queryWrapper.orderByDesc("create_time");
        }
        List<EnterpriseImprove> enterpriseImproves = enterpriseImproveMapper.selectList(queryWrapper);
        for (EnterpriseImprove enterpriseImprove : enterpriseImproves) {
            //查询部门管理者id
            EnterpriseOrganization enterpriseOrganization = enterpriseOrganizationMapper.selectById(enterpriseImprove.getEnterpriseOrganizationId());
            if (enterpriseOrganization != null && enterpriseOrganization.getWxUserId() != null) {
                enterpriseImprove.setCheckWxUserId(enterpriseOrganization.getWxUserId());
            }
            //设置用户信息
            setWxUser(enterpriseImprove, enterpriseImprove.getWxUserId());
            //设置分类
            setCommonCategory(enterpriseImprove, enterpriseImprove.getCommonCategoryId());
        }
        return new ReturnVO("企业改善列表查询成功", new JgPageVo<>(new PageInfo(enterpriseImproves)));
    }

    @Override
    public ReturnVO<EnterpriseImprove> selectEnterpriseImproveDetail(Long enterpriseImproveId) {
        EnterpriseImprove enterpriseImprove = enterpriseImproveMapper.selectById(enterpriseImproveId);
        Optional.ofNullable(enterpriseImprove).orElseThrow(() -> new ServiceException("该改善已不存在"));
        //查询部门管理者id
        EnterpriseOrganization enterpriseOrganization = enterpriseOrganizationMapper.selectById(enterpriseImprove.getEnterpriseOrganizationId());
        if (enterpriseOrganization != null && enterpriseOrganization.getWxUserId() != null) {
            enterpriseImprove.setCheckWxUserId(enterpriseOrganization.getWxUserId());
        }
        //设置用户信息
        setWxUser(enterpriseImprove, enterpriseImprove.getWxUserId());
        //设置分类
        setCommonCategory(enterpriseImprove, enterpriseImprove.getCommonCategoryId());
        return new ReturnVO("企业改善详情查询成功", enterpriseImprove);
    }

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private EnterpriseOrganizationMapper enterpriseOrganizationMapper;

    @Override
    public ReturnVO wxUpdateEnterpriseImprove(Long wxUserId, EnterpriseImproveUpdateDto enterpriseImproveUpdateDto) {
        EnterpriseImprove enterpriseImprove = enterpriseImproveMapper.selectById(enterpriseImproveUpdateDto.getEnterpriseImproveId());
        Optional.ofNullable(enterpriseImprove).orElseThrow(() -> new ServiceException("该改善已不存在"));
        WxUser sendWxUser = wxUserMapper.selectById(enterpriseImprove.getWxUserId());
        Optional.ofNullable(sendWxUser).orElseThrow(() -> new ServiceException("发布改善的用户已不存在"));
        WxUser wxUser = wxUserMapper.selectById(wxUserId);
        Optional.ofNullable(wxUser).orElseThrow(() -> new ServiceException("用户不存在"));
        EnterpriseOrganization enterpriseOrganization = enterpriseOrganizationMapper.selectById(sendWxUser.getEnterpriseOrganizationId());
        if (enterpriseOrganization.getWxUserId() == null || !enterpriseOrganization.getWxUserId().equals(wxUser.getId())) {
            throw new ServiceException("你不是该改善对应部门的管理者,无法审核");
        }
        enterpriseImprove.setStatus(enterpriseImproveUpdateDto.getStatus());
        enterpriseImprove.setReturnRemark(enterpriseImproveUpdateDto.getReturnRemark());
        enterpriseImproveMapper.updateById(enterpriseImprove);
        return new ReturnVO("企业改善审核成功", enterpriseImprove.getId());
    }

    @Override
    public ReturnVO updateEnterpriseImprove(EnterpriseImproveUpdateDto enterpriseImproveUpdateDto) {
        EnterpriseImprove enterpriseImprove = enterpriseImproveMapper.selectById(enterpriseImproveUpdateDto.getEnterpriseImproveId());
        Optional.ofNullable(enterpriseImprove).orElseThrow(() -> new ServiceException("该改善已不存在"));
        enterpriseImprove.setStatus(enterpriseImproveUpdateDto.getStatus());
        enterpriseImprove.setReturnRemark(enterpriseImproveUpdateDto.getReturnRemark());
        enterpriseImproveMapper.updateById(enterpriseImprove);
        if (enterpriseImproveUpdateDto.getStatus() != null && enterpriseImproveUpdateDto.getStatus() == 1) {
            //todo 小程序订阅
            SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
            systemMessageMqDto.setMessageDetail("恭喜你,您发布的:" + enterpriseImprove.getImproveTitle() + "改善已于" + LocalDateTime.now() + "审核通过");
            systemMessageMqDto.setMessageTitle("改善成果审核通过");
            systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
                {
                    add(enterpriseImprove.getWxUserId());
                }
            });
            userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        }
        return new ReturnVO("企业改善审核成功", enterpriseImprove.getId());
    }

    @Override
    public ReturnVO deleteEnterpriseImprove(Long enterpriseImproveId) {
        EnterpriseImprove enterpriseImprove = enterpriseImproveMapper.selectById(enterpriseImproveId);
        Optional.ofNullable(enterpriseImprove).orElseThrow(() -> new ServiceException("该改善已不存在"));
        enterpriseImproveMapper.deleteById(enterpriseImproveId);
        //todo 小程序订阅
        SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
        systemMessageMqDto.setMessageDetail("很抱歉,您发布的:" + enterpriseImprove.getImproveTitle() + "改善成果因违规已被管理员删除,详情请在小程序内查看");
        systemMessageMqDto.setMessageTitle("改善成果");
        systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
            {
                add(enterpriseImprove.getWxUserId());
            }
        });
        userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        return new ReturnVO("企业改善删除成功", enterpriseImproveId);
    }

    @Autowired
    private UserMessageProducer userMessageProducer;

    @Autowired
    private CommonCategoryMapper commonCategoryMapper;

    @Override
    public ReturnVO listMyEnterpriseImprove(Long wxUserId, MyEnterpriseImproveDto myEnterpriseImproveDto) {
        PageHelper.startPage(myEnterpriseImproveDto.getCurPage(), myEnterpriseImproveDto.getMaxPage());
        QueryWrapper<EnterpriseImprove> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wx_user_id", wxUserId);
        queryWrapper.orderByDesc("create_time");

        Optional.ofNullable(myEnterpriseImproveDto.getStatus()).ifPresent(e -> queryWrapper.eq("status", e));
        List<EnterpriseImprove> enterpriseImproves = enterpriseImproveMapper.selectList(queryWrapper);
        for (EnterpriseImprove enterpriseImprove : enterpriseImproves) {
            //设置分类
            setCommonCategory(enterpriseImprove, enterpriseImprove.getCommonCategoryId());
        }
        return new ReturnVO("我的改善列表查询成功", new JgPageVo<>(new PageInfo(enterpriseImproves)));
    }

    @Override
    public ReturnVO<JgPageVo<List<EnterpriseImprove>>> listMyCheckEnterpriseImprove(Long wxUserId, MyCheckEnterpriseImproveDto myCheckEnterpriseImproveDto) {
        PageHelper.startPage(myCheckEnterpriseImproveDto.getCurPage(), myCheckEnterpriseImproveDto.getMaxPage());
        List<EnterpriseImprove> enterpriseImproves = enterpriseImproveMapper.listMyCheckEnterpriseImprove(wxUserId, myCheckEnterpriseImproveDto);
        for (EnterpriseImprove enterpriseImprove : enterpriseImproves) {
            //查询部门管理者id
            EnterpriseOrganization enterpriseOrganization = enterpriseOrganizationMapper.selectById(enterpriseImprove.getEnterpriseOrganizationId());
            if (enterpriseOrganization != null && enterpriseOrganization.getWxUserId() != null) {
                enterpriseImprove.setCheckWxUserId(enterpriseOrganization.getWxUserId());
            }
            //设置用户信息
            setWxUser(enterpriseImprove, enterpriseImprove.getWxUserId());
            //设置分类
            setCommonCategory(enterpriseImprove, enterpriseImprove.getCommonCategoryId());
        }
        return new ReturnVO("我的审核查询成功", new JgPageVo<>(new PageInfo(enterpriseImproves)));
    }

    @SneakyThrows
    @Override
    public ReturnVO<JgPageVo<List<FeignWxUserDto>>> selectSumByEnterpriseImprove(HttpServletResponse response, Long enterpriseId, SumByEnterpriseImproveDto sumByEnterpriseImproveDto) {
        PageHelper.startPage(sumByEnterpriseImproveDto.getCurPage(), sumByEnterpriseImproveDto.getMaxPage());
        String startTime = null;
        String endTime = LocalDate.now().toString();
        //近7天
        if (sumByEnterpriseImproveDto.getLastDay() == 0) {
            startTime = LocalDate.now().minusDays(7).toString();
        }
        //近30天
        if (sumByEnterpriseImproveDto.getLastDay() == 1) {
            startTime = LocalDate.now().minusDays(30).toString();
        }
        //近365天
        if (sumByEnterpriseImproveDto.getLastDay() == 2) {
            startTime = LocalDate.now().minusDays(365).toString();
        }
        //查询用户信息
        List<EnterpriseImprove> enterpriseImproves = enterpriseImproveMapper.selectSumByEnterpriseImprove(enterpriseId, startTime, endTime);
        List<FeignWxUserDto> feignWxUserDtoList = Lists.newArrayList();
        List<SelectSumByEnterpriseImproveVo> selectSumByEnterpriseImproveVos = Lists.newArrayList();
        for (EnterpriseImprove enterpriseImprove : enterpriseImproves) {
            FeignWxUserDto feignWxUserDto = wxUserService.selectFeignWxUserDtoByWxUserId(enterpriseImprove.getWxUserId());
            feignWxUserDto.setImproveNum(enterpriseImprove.getImproveNum());
            feignWxUserDtoList.add(feignWxUserDto);
            //导出
            SelectSumByEnterpriseImproveVo selectSumByEnterpriseImproveVo = new SelectSumByEnterpriseImproveVo();
            BeanUtils.copyProperties(feignWxUserDto, selectSumByEnterpriseImproveVo);
            selectSumByEnterpriseImproveVos.add(selectSumByEnterpriseImproveVo);
        }
        if (sumByEnterpriseImproveDto.getIsExport() != null && sumByEnterpriseImproveDto.getIsExport() == 1) {
            ExcelUtils.exportExcel(selectSumByEnterpriseImproveVos, "改善之星", "改善之星", SelectSumByEnterpriseImproveVo.class, "改善之星", response);
            return new ReturnVO("改善之星导出成功", null);
        }
        return new ReturnVO("改善之星查询成功", new JgPageVo<>(new PageInfo(enterpriseImproves)));
    }

    @Override
    public Integer selectWxUserCenterImprove(Long wxUserId) {
        return enterpriseImproveMapper.selectCount(new LambdaQueryWrapper<EnterpriseImprove>()
                .eq(EnterpriseImprove::getWxUserId, wxUserId)
                .eq(EnterpriseImprove::getStatus, 1));
    }

    @Override
    public ReturnVO<EnterpriseImproveVo> selectEnterpriseImproveVo(Long enterpriseId) {
        EnterpriseImproveVo enterpriseImproveVo = new EnterpriseImproveVo();
        String weekendStartTime = LocalDate.now().minusDays(7).toString();
        String monthStartTime = LocalDate.now().minusDays(30).toString();
        Integer weekendStartTimeNum = enterpriseImproveMapper.selectEnterpriseImproveVo(enterpriseId, weekendStartTime, LocalDate.now().plusDays(1).toString());
        Integer monthStartTimeNum = enterpriseImproveMapper.selectEnterpriseImproveVo(enterpriseId, monthStartTime, LocalDate.now().plusDays(1).toString());
        Integer allEnterpriseImproveNum = enterpriseImproveMapper.selectAllEnterpriseImproveNum(enterpriseId);
        enterpriseImproveVo.setWeekendNum(weekendStartTimeNum);
        enterpriseImproveVo.setMonthNum(monthStartTimeNum);
        enterpriseImproveVo.setAllNum(allEnterpriseImproveNum);
        return new ReturnVO("改善统计查询成功", enterpriseImproveVo);
    }

    @Autowired
    private IWxUserService wxUserService;

    //设置用户信息
    private void setWxUser(EnterpriseImprove enterpriseImprove, Long wxUserId) {
        Optional.ofNullable(wxUserId).orElseThrow(() -> new ServiceException("发布改善的用户已不存在"));
        //查询用户信息
        WxUser wxUser = wxUserMapper.selectById(enterpriseImprove.getWxUserId());
        Optional.ofNullable(wxUser).ifPresent(e -> {
            enterpriseImprove.setNickname(e.getNickname());
            enterpriseImprove.setIcon(e.getIcon());
            FeignWxUserDto feignWxUserDto = wxUserService.selectFeignWxUserDtoByWxUserId(wxUserId);
            enterpriseImprove.setOrganizationName(feignWxUserDto.getOrganizationName());
            enterpriseImprove.setLastOrganizationName(feignWxUserDto.getLastOrganizationName());
            enterpriseImprove.setIdentityName(feignWxUserDto.getIdentityName());
            enterpriseImprove.setPhone(feignWxUserDto.getPhone());
        });
    }

    //设置分类
    private void setCommonCategory(EnterpriseImprove enterpriseImprove, Long commonCategoryId) {
        //查询分类名
        CommonCategory commonCategory = commonCategoryMapper.selectById(commonCategoryId);
        Optional.ofNullable(commonCategory).ifPresent(e -> enterpriseImprove.setCategoryName(e.getCategoryName()));
    }
}
